package com.flame.schedule.executor;

import com.flame.core.utils.DateUtils;
import com.flame.schedule.constants.JobConstants;
import com.flame.schedule.entity.JobInfo;
import com.flame.schedule.entity.JobLog;
import com.flame.schedule.executor.JobExecutor;
import com.flame.schedule.service.JobLogService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;

@Service
public class ExecutorService implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Autowired
    private JobLogService jobLogService;

    public void execute(JobInfo jobInfo) {
        JobLog jobLog = new JobLog();
        BeanUtils.copyProperties(jobInfo, jobLog);
        long start = System.currentTimeMillis();
        jobLog.setStartTime(DateUtils.currentDateTime());
        try {
            JobExecutor jobExecutor = applicationContext.getBean(jobInfo.getBeanName(), JobExecutor.class);
            jobExecutor.execute(jobInfo.getJobData());
            jobLog.setResult(JobConstants.EXECUTE_SUCCESS);
        } catch (Exception e) {
            jobLog.setResult(JobConstants.EXECUTE_FAILED);
            jobLog.setRemark(e.getMessage());
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        jobLog.setDuration((double) (end - start) / 1000);
        jobLogService.addJobLog(jobLog);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
